package com.sdx.console.templateapp.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.templateapp.entity.*;
import com.sdx.console.templateapp.service.*;
import com.sdx.console.templateapp.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * TemplateApp 接口
 */
@RequestMapping("/templateapp/templateApp")
@Controller
public class TemplateAppController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(TemplateAppController.class);
    private static final String MODEL = "/templateapp/templateApp";


    @Resource
	private TemplateAppService templateAppService;

	@Resource
	private ResCloudFileService resCloudFileService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

	}

    /* 页面 */

    @GetMapping("/index.do")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request,Integer templateType,String linkId) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
		view.addObject("templateType", templateType);
		view.addObject("linkId", linkId);
        return view;
    }

    @GetMapping("/edit.do")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer templateId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        TemplateApp templateApp = templateAppService.queryById(templateId);
        view.addObject("templateApp", templateApp);
		view.addObject("templateType", templateApp.getTemplateId());
		view.addObject("linkId", templateApp.getLinkId());
		setPageParam(view,request);
		try {
			view.addObject("templateAppJson", JacksonUtils.toJsonString(templateApp,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request,Integer templateType,String linkId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
		view.addObject("templateType", templateType);
		view.addObject("linkId", linkId);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @ResponseBody
    public JsonResult<PageQuery> list(TemplateApp condtion)
    {
        PageQuery page = condtion.getPageQuery();
        templateAppService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,TemplateApp templateApp,HttpServletRequest request
							,MultipartFile templateImgFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/templateapp/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(templateImgFile)) {
			try
			{
		        String templateImgFileNamePair = FileUtils.upload(subPath,templateImgFile);
		        String templateImgStoreFile = templateImgFileNamePair.split("::")[0];
		        templateImgStoreFile = subPath+templateImgStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+templateImgStoreFile,bucketName,templateImgStoreFile.substring(1));
				String templateImgUrl = "https://sdxcomm."+ ConfigService.ossDomain+templateImgStoreFile;
				templateApp.setTemplateImg(templateImgUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,templateImgStoreFile,templateImgUrl,"a","模板图片");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			templateApp.setCreatedBy(user.getId().intValue());
			templateApp.setCreatedName(user.getName());
			templateApp.setCreatedTime(new Date());
			templateApp.setUpdatedBy(user.getId().intValue());
			templateApp.setUpdatedName(user.getName());
			templateApp.setUpdatedTime(new Date());
			templateAppService.save(templateApp);
		} else {
			templateApp.setUpdatedBy(user.getId().intValue());
			templateApp.setUpdatedName(user.getName());
			templateApp.setUpdatedTime(new Date());
			templateAppService.updateTemplate(templateApp);
		}
		return result;
	}
    @PostMapping("/add.json")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)TemplateApp templateApp,HttpServletRequest request
							,@RequestParam("templateImgFile") MultipartFile templateImgFile
		)
    {

        return save(true,templateApp,request
					,templateImgFile
		);
    }

    @PostMapping("/update.json")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  TemplateApp templateApp,HttpServletRequest request
							,@RequestParam("templateImgFile") MultipartFile templateImgFile
		) {
		return save(false,templateApp,request
		,templateImgFile
		);
    }


   
    @GetMapping("/view.json")
    @ResponseBody
    public JsonResult<TemplateApp>queryInfo(Integer templateId) {
        TemplateApp templateApp = templateAppService.queryById( templateId);
        return  JsonResult.success(templateApp);
    }

    @PostMapping("/delete.json")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        templateAppService.batchDelTemplateApp(idList);
        return JsonResult.success();
    }
    

}
